package weibo.service;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSONObject;

import weibo.database.PraiseDB;
import weibo.model.UserMod;
import weibo.model.ReplyMod;
import weibo.database.PraiseDB;


/**
 * Servlet implementation class clickpraise
 */
@WebServlet("/clickpraise")
public class clickpraise extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public clickpraise() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		HttpSession session = request.getSession();
		List<UserMod> user = (List<UserMod>) session.getAttribute("user");
		int UserID = user.get(0).getUserid();
		String TYPE = request.getParameter("type");
		int tweet_id = Integer.parseInt(request.getParameter("tweetid"));
		PraiseDB praise = new PraiseDB();
		if (user != null) {
			switch (TYPE) {
			// 添加点赞
			case "addpraise":
				if (praise.CreatePraise(tweet_id, UserID)) {
					System.out.println("点赞成功");
					response.getWriter().append("success");
				} else {
					System.out.println("点赞失败");
					response.getWriter().append("error");
				}
				break;
			// 添加回复
			case "addreply":
				String text = request.getParameter("text");
				if (praise.CreateReply(tweet_id, UserID, text)) {
					response.getWriter().append("success");
				} else {
					response.getWriter().append("error");
				}
				break;
			// 查询回复
			case "queryreply":
				int start=Integer.parseInt(request.getParameter("start"));
				int len=Integer.parseInt(request.getParameter("len"));
				List<ReplyMod> reply=null;
				reply=praise.QueryTweetReply(tweet_id, start, len);
				JSONObject json=new JSONObject();
				json.put("reply", reply);
				response.getWriter().append(json.toJSONString());
				break;
			}

		}
	}

}
